import React from 'react';
import {Spin, Popconfirm, Table, Card, Collapse, Button, Row, Col, Form, Message as msg} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, FORM_ROW_OPTIONS, TABLE, FIXED_COLUMN_WIDTH} from '../constants';
import {addApplyReport} from './api';
import TextInput from 'Shared/components/TextInput';
import SearchInput from 'Shared/components/SearchInput';
import DutyUnitSelectPanel from './DutyUnitSelectPanel';
import WrappedDatePicker from '../common/WrappedDatePicker';
import {injectIntl} from './intl';
import WrappedSelect from '../common/WrappedSelect';
import PartPanel from './PartSelectPanel';
import styles from './style.css';
import Return from '../common/Return';
import {newOrderValidator} from './validator';
const FormItem = Form.Item;

class AddPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        showPartPanel: false,

        showDutyUnitSelectPanel: false,
        showReplaceDutyUnitSelectPanel: false,
        data: {},
        parts: []
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const {data, parts} = this.state;
        const isValid = newOrderValidator(data);
        const partsIds = [];
        if(!isValid) {
            this.setState({
                isValidate: true
            });
            return;
        }
        if(parts)
            for(const d of parts)
                partsIds.push(d.id);
        const condition = {
            brandId: data.brandId,
            dutyUnitId: data.dutyUnitId,
            replacedDutyUnitId: data.replacedDutyUnitId,
            // parts: partsIds,
            parts: parts.map(v => ({
                id: v.id,
            })),
            remark: data.remark,
            startTime: data.startTime,
            endTime: data.endTime,
        };
        this.setState({loading: true});
        addApplyReport(condition).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onClickSearchDutyUnitBtn = () => {
        this.setState({
            showDutyUnitSelectPanel: true
        });
    }
    onClickSearchReplaceDutyUnitBtn = () => {
        this.setState({
            showReplaceDutyUnitSelectPanel: true
        });
    }
    onCloseDutyUnitSelectPanel = () => {
        this.setState({showDutyUnitSelectPanel: false});
    }
    onCloseReplaceDutyUnitSelectPanel = () => {
        this.setState({showReplaceDutyUnitSelectPanel: false});
    }
    onSelectDutyUnit = records => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                dutyUnitId: records.id,
                dutyUnitCode: records.code,
                dutyUnitName: records.name,
            }),
            hasOperat: true,
            showDutyUnitSelectPanel: false
        });
    }
    onSelectReplaceDutyUnit = records => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                replacedDutyUnitId: records.id,
                replacedDutyUnitCode: records.code,
                replacedDutyUnitName: records.name,
            }),
            hasOperat: true,
            showReplaceDutyUnitSelectPanel: false
        });
    }
    // 删除清单
    onDeleteAll = () => {
        this.setState({
            parts: [],
            hasOperat: true
        });
    }
    onDeleteDetail = e => {
        const partId = e.target.dataset.id;
        const tmp = this.state.parts.filter(d => d.id !== partId);
        this.setState({
            parts: [...tmp],
            hasOperat: true
        });
    }
    onSelectPart = records => {
        const retailDetails = this.state.parts || [];
        records.forEach(r => {
            const index = retailDetails.findIndex(v => v.id === r.id);
            if(index === -1)
                retailDetails.push({
                    id: r.id,
                    code: r.code,
                    name: r.name
                });
        });
        this.setState({
            parts: [...retailDetails],
            hasOperat: true,
            showPartPanel: false
        });
    }
    onClickAddBtn = () => {
        this.setState({showPartPanel: true});
    }
    onClosePartPanel = () => {
        this.setState({showPartPanel: false});
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, parts, isValidate, loading} = this.state;
        const {brands} = this.props.initEnumData;
        if(brands.length === 1 && !this.props.id) {
            data.brandId = brands[0].value;
            data.brandName = brands[0].text;
        }
        const colums = [{
            title: formatMessage({
                id: 'newPanel.column.code',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'code',
        }, {
            title: formatMessage({
                id: 'newPanel.column.name',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'name',
        }, {
            title: parts && parts.length > 0
                ? (
                    <Popconfirm placement="topRight" title={formatMessage({
                        id: 'newPanel.column.allDelete',
                        defaultMessage: '是否确认全部删除？'
                    })} onConfirm={this.onDeleteAll} >
                        <a>{formatMessage({
                            id: 'newPanel.column.empty',
                            defaultMessage: '清空'
                        })}</a>
                    </Popconfirm>
                )
                : <a>{formatMessage({
                    id: 'newPanel.column.empty',
                    defaultMessage: '清空'
                })}</a>,
            dataIndex: 'id',
            fixed: 'right',
            width: FIXED_COLUMN_WIDTH,
            render: text => <a data-id={text} onClick={this.onDeleteDetail}>{formatMessage({
                id: 'newPanel.column.delete',
                defaultMessage: '删除'
            })}</a>
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'addPanel.column.common',
                        defaultMessage: '供应商替换关系信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.code',
                                        defaultMessage: '编号'
                                    })}{...FORM_OPTIONS.item}>
                                        <span className="value-font">{formatMessage({
                                            id: 'addPanel.value.defalut',
                                            defaultMessage: '尚未生成'
                                        })}</span>
                                    </FormItem>
                                </Col>
                                {brands.length !== 1 && <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.brandName',
                                        defaultMessage: '品牌'
                                    })}{...FORM_OPTIONS.item} validateStatus={isValidate && !data.brandId ? 'error' : null} required>
                                        <WrappedSelect
                                            name="brandId"
                                            value={data.brandId}
                                            options={brands}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.dutyUnitId',
                                        defaultMessage: '原供应商'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.dutyUnitId ? 'error' : null} required>
                                        <SearchInput
                                            disabled={true}
                                            value={data.dutyUnitCode === undefined ? '' : `(${data.dutyUnitCode})${data.dutyUnitName}`}
                                            onClickSearchBtn={() => this.onClickSearchDutyUnitBtn()} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.operation.replacedDutyUnitId',
                                        defaultMessage: '替换供应商'
                                    })} {...FORM_OPTIONS.item} validateStatus={isValidate && !data.replacedDutyUnitId ? 'error' : null} required>
                                        <SearchInput
                                            disabled={true}
                                            value={data.replacedDutyUnitId === undefined ? '' : `(${data.replacedDutyUnitCode})${data.replacedDutyUnitName}`}
                                            onClickSearchBtn={() => this.onClickSearchReplaceDutyUnitBtn()} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.startTime',
                                            defaultMessage: '开始时间'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={isValidate && !data.startTime ? 'error' : null}
                                        required>
                                        <WrappedDatePicker
                                            name="startTime"
                                            value={data.startTime}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.endTime',
                                            defaultMessage: '结束时间'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={isValidate && !data.endTime ? 'error' : null}
                                        required>
                                        <WrappedDatePicker
                                            name="endTime"
                                            value={data.endTime}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row className="row-margin">
                                <Col>
                                    <FormItem label={formatMessage({
                                        id: 'addPanel.text.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_ROW_OPTIONS.item}>
                                        <TextInput
                                            type="textarea"
                                            name="remark"
                                            value={data.remark}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'newPanel.operation.detail',
                            defaultMessage: '备件清单'
                        })}
                        extra={<div>
                            <Button
                                size="small"
                                onClick={this.onClickAddBtn}>
                                {formatMessage({
                                    id: 'newPanel.operation.newDetail',
                                    defaultMessage: '新增'
                                })}
                            </Button>
                        </div>}>
                        <Table
                            className="white-space-nowrap"
                            columns={colums}
                            rowKey="id"
                            pagination={false}
                            dataSource={parts}
                            {...TABLE} />
                    </Card>
 
                    
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={loading}>
                            {formatMessage({
                                id: 'addPanel.operation.onSubmit',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                {
                    this.state.showPartPanel &&
                        <PartPanel
                            currentSelectRowkeys={parts}
                            selectKey={parts.id}
                            onCancel={this.onClosePartPanel}
                            onSelect={this.onSelectPart} />
                }
                {
                    this.state.showDutyUnitSelectPanel &&
                    <DutyUnitSelectPanel
                        selectKey={data.dutyUnitId}
                        onCancel={this.onCloseDutyUnitSelectPanel}
                        onSelect={this.onSelectDutyUnit} />
                }
                {
                    this.state.showReplaceDutyUnitSelectPanel &&
                    <DutyUnitSelectPanel
                        selectKey={data.replacedDutyUnitId}
                        onCancel={this.onCloseReplaceDutyUnitSelectPanel}
                        onSelect={this.onSelectReplaceDutyUnit} />
                }
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

AddPanel.propTypes = {
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSelect: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    saveQueryDealer
} from './actions';
import {createSelector} from 'reselect';

const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'init']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands ? initData.brands.map(item => ({
            text: `(${item.code})${item.name}`,
            value: item.id
        })) : [];
        return {
            brands,
        };
    }
);
const mapStateToProps = state => ({
    initEnumData: getinitEnumData(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSelect: data => dispatch(saveQueryDealer(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(AddPanel));
